package com.web22_2_1.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import com.web22_2_1.entity.User;
import com.web22_2_1.service.UserService;
import com.web22_2_1.service.impl.UserServiceImpl;
import com.web22_2_1.utils.JwtUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet{
	private UserService userService = new UserServiceImpl();
	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
		response.setContentType("text/html;charset = utf-8");
		
		String userName = request.getParameter("username");
		String password = request.getParameter("password");
		User user = userService.getUser(userName, password);
		if(user!=null){
			Map<String, Object> claims = new HashMap<>();
			claims.put("userId", user.getUserId());
			String token = JwtUtil.createJWT(claims);
			HttpSession session = request.getSession();
			session.setAttribute("token", token);
			response.sendRedirect(request.getContextPath() + "/index.jsp");
		}
		else{
			PrintWriter out = response.getWriter();
			out.print("用户名或密码错误，返回<a href=\'login.jsp\'>登录</a>");
			response.setHeader("refresh","3;url = login.jsp");//失败后三秒跳转登录页
		}
	}
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		super.doGet(request, response);
	}
}
